<?php

if(isset($_POST['password']) && isset($_POST['username'])){
#if it is a logon request

  #Get username and password from post
  $password = md5($_POST['password']);
  $username =     $_POST['username'];

  #Require usr db model
  require_once $BASE_PATH . 'm/usr.php';
  $usrcn = new USR(DBHOST, DBUSER, DBPASS, DBNAME);

  #check username exist
  $userInfo = $usrcn->get($username);

  if($_POST['password'] === '' || $_POST['username'] === ''){
    echo '{"code": 3, "message": "invalid data"}';
  }else if($userInfo === false){
  #if username not exist

    #add usr to db
    $usrcn->add($username, $password);

    #check again
    $userInfo = $usrcn->get($username);

    if($userInfo !== false){

      $_SESSION['usr'] = $userInfo['uid'];
      $UID = $_SESSION['usr'];

      #Require dir db model
      require_once $BASE_PATH . 'm/dir.php';
      $dircn = new DIR(DBHOST, DBUSER, DBPASS, DBNAME);

      $dircn->add(0, 'basefolder', $UID);

      echo '{"code": 0}';

    }else{

      echo '{"code": 2, "message": "fail to add user"}';

    }

  }else{

    echo '{"code": 1, "message": "username existed"}';

  }
}
